#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;

void* MasterCore(void* args)
{
    sleep(3);
    const char* name = static_cast<const char*>(args);
    std::cout << "master 开始工作\n";
    while(true)
    {
        pthread_cond_signal(&gCond);
        std::cout << "master 唤醒一个线程\n";
        sleep(1);
    }
}

void* SlaverCore(void* args)
{
    std::string* name = static_cast<std::string*>(args);
    while(true)
    {
        pthread_mutex_lock(&gMutex);

        pthread_cond_wait(&gCond, &gMutex);
        std::cout << "当前被唤醒的线程 : " << *name << std::endl;

        pthread_mutex_unlock(&gMutex);

    }
}

void StartMaster(std::vector<pthread_t>& tids)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, static_cast<void*>(const_cast<char*>("Master")));
    if(n == 0)
    {
        std::cout << "create master thread success\n";
        tids.emplace_back(tid);
    }
}

void StartSlaver(std::vector<pthread_t>& tids, int num)
{
    for (int i = 0; i < num; i++)
    {
        pthread_t tid;
        char buff[128];
        snprintf(buff, sizeof buff, "Slaver-%d", i + 1);
        std::string* s = new std::string(buff);
        int n = pthread_create(&tid, nullptr, SlaverCore, static_cast<void*>(s));
        if(n == 0)
        {
            std::cout << "create " << buff << " success\n";
            tids.emplace_back(tid);
        }
    }
}

void WaitAll(std::vector<pthread_t>& tids)
{
    for (auto& tid : tids)
        pthread_join(tid, nullptr);
}

int main()
{
    std::vector<pthread_t> tids;
    StartMaster(tids);
    StartSlaver(tids, 5);
    WaitAll(tids);
    return 0;
}